//
//  AppDelegate.m
//  CollectCrashDemo
//
//  Created by Hello Cai on 2020/11/22.
//

#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    NSSetUncaughtExceptionHandler(handleException);
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    ViewController *vc = [[ViewController alloc] init];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    
    return YES;
}

void handleException(NSException *exception)
{
    NSString* name   = [exception name];
    NSString* reason = [exception reason];
    NSArray* symbols = [exception callStackSymbols]; // 异常发生时的调用栈
    NSMutableString* strSymbols = [[NSMutableString alloc] init]; //将调用栈拼成输出日志的字符串
    for (NSString* item in symbols)
    {
        [strSymbols appendString: @"\t"];
        [strSymbols appendString: item];
        [strSymbols appendString: @"\r\n"];
    }
    NSDateFormatter *dformatter = [[NSDateFormatter alloc] init];
    [dformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [dformatter stringFromDate:[NSDate date]];
    
    NSString *crashString = [NSString stringWithFormat:@"<- %@ ->[Uncaught Exception]\r\nName: %@, Reason: %@\r\n[Fe Symbols Start]\r\n%@[Fe Symbols End]\r\n\r\n", dateStr, name, reason, strSymbols];
    NSLog(@"==========%@",crashString);
    // [crashString writeToFile:<#(NSString *)#> atomically:<#(BOOL)#>];
    
    //将crash日志保存到Document目录下的Log文件夹下
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"documentPath:%@",documentPath);
    NSString *logFilePath = [documentPath stringByAppendingPathComponent:@"UncaughtException.log"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把错误日志写到文件中
    if (![fileManager fileExistsAtPath:logFilePath]) {
        [crashString writeToFile:logFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }else{
        NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
        [outFile seekToEndOfFile];
        [outFile writeData:[crashString dataUsingEncoding:NSUTF8StringEncoding]];
        [outFile closeFile];
    }
}


#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}


@end
